<template>
  <div class="logs-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>执行日志</span>
          <el-button type="primary" @click="refreshLogs">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form" v-if="false">
        <el-form-item label="服务名称">
          <el-input 
            v-model="searchForm.serviceName" 
            placeholder="请输入服务名称"
            clearable
            style="width: 200px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="方法名称">
          <el-input 
            v-model="searchForm.serviceMethod" 
            placeholder="请输入方法名称"
            clearable
            style="width: 200px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="全部"
            clearable
            style="width: 120px;"
          >
            <el-option label="成功" value="success"></el-option>
            <el-option label="失败" value="error"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchLogs" :loading="searchLoading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 日志表格 -->
      <el-table :data="logList" stripe v-loading="tableLoading" empty-text="暂无日志" :fit="false">
        <el-table-column prop="logTime" label="日志时间" width="180" sortable>
          <template #default="scope">
            <el-tooltip :content="scope.row.logTime" placement="top">
              <span>{{ formatTime(scope.row.logTime) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="日志级别" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.level === 'ERROR' ? 'danger' : scope.row.level === 'WARN' ? 'warning' : 'info'">{{ scope.row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="thread" label="线程" width="120"></el-table-column>
        <el-table-column prop="logger" label="日志来源" width="250"></el-table-column>
        <el-table-column prop="message" label="日志内容" width="400"></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showDetails(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>


      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px; text-align: right;"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>

      <!-- 日志详情对话框 -->
      <el-dialog v-model="dialogVisible" title="日志详情" width="800px">
        <div class="log-details">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="日志时间">{{ currentLog?.logTime }}</el-descriptions-item>
            <el-descriptions-item label="日志级别">
              <el-tag :type="currentLog?.level === 'ERROR' ? 'danger' : currentLog?.level === 'WARN' ? 'warning' : 'info'">{{ currentLog?.level }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="线程">{{ currentLog?.thread }}</el-descriptions-item>
            <el-descriptions-item label="日志来源">{{ currentLog?.logger }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentLog?.createTime }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="log-content">
            <h4>执行详情：</h4>
            <el-input :model-value="currentLog?.message || ''" type="textarea" :rows="10" readonly placeholder="暂无日志内容"></el-input>
          </div>
        </div>
        
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="copyDetails" v-if="currentLog?.details">
            复制详情
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { taskApi } from '../api/taskApi';

const logList = ref([])
const searchLoading = ref(false)
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const dialogVisible = ref(false)
const currentLog = ref(null)

const searchForm = reactive({
  serviceName: '',
  serviceMethod: '',
  status: '',
  dateRange: undefined
})

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm:ss')
}

// 搜索日志
const searchLogs = async () => {
  try {
    searchLoading.value = true
    currentPage.value = 1
    await fetchLogs()
    ElMessage.success('搜索完成')
  } catch (error) {
    console.error('搜索日志失败:', error)
    ElMessage.error('搜索日志失败')
  } finally {
    searchLoading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.serviceName = ''
  searchForm.serviceMethod = ''
  searchForm.status = ''
  searchForm.dateRange = undefined
  searchLogs()
}

// 刷新日志
const refreshLogs = () => {
  fetchLogs()
}

// 获取日志数据
const fetchLogs = async () => {
  tableLoading.value = true;
  try {
    const response = await taskApi.getSysLogs({
      pageNo: currentPage.value,
      pageSize: pageSize.value
    });
    const data = response.data.data;
    total.value = data.total;
    logList.value = data.records.map(log => ({
      ...log,
      logTime: String(log.logTime)
    }));
    console.log('已加载日志数据，共', data.records.length, '条记录');
    ElMessage.success(`成功加载 ${logList.value.length} 条日志`);
  } catch (error) {
    console.error('加载日志失败:', error);
    ElMessage.error('加载日志失败');
  } finally {
    tableLoading.value = false;
  }
}

// 分页处理
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchLogs()
}

// 组件挂载时自动获取日志数据
onMounted(() => {
  fetchLogs();
});

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchLogs()
}

// 显示详情
const showDetails = (log: any) => {
  currentLog.value = log
  dialogVisible.value = true
}

// 复制详情
const copyDetails = async () => {
  if (!currentLog.value?.details) return
  
  try {
    await navigator.clipboard.writeText(currentLog.value.details)
    ElMessage.success('详情已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.logs-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

/* 夜间模式适配 */
:global(body.dark) .search-form {
  background: #23272e;
}
:global(body.dark) .search-form .el-input__wrapper,
:global(body.dark) .search-form .el-select .el-input__wrapper,
:global(body.dark) .search-form .el-date-editor.el-input__wrapper {
  background: #23272e !important;
  color: #e0e0e0 !important;
  border-color: #444 !important;
}
:global(body.dark) .search-form .el-input__inner,
:global(body.dark) .search-form .el-select__selected-item,
:global(body.dark) .search-form .el-date-editor .el-input__inner {
  background: #23272e !important;
  color: #e0e0e0 !important;
}

/* 新增：夜间模式下的重置按钮样式 */
:global(body.dark) .search-form .el-button:not(.el-button--primary) {
  background-color: #23272e !important;
  color: #e0e0e0 !important;
  border-color: #444 !important;
}

.log-details {
  .log-content {
    margin-top: 20px;
    
    h4 {
      margin: 0 0 10px 0;
      color: #303133;
    }
  }
}

.text-warning {
  color: #e6a23c;
  font-weight: bold;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

/* 确保表格宽度固定 */
:deep(.el-table) {
  width: 1150px !important; /* 所有列宽度总和 + 滚动条宽度 */
}
</style>
